package cn.dslcode.security.config.oauth2;

import cn.dslcode.security.config.CustomAuthenticationHandlers;
import cn.dslcode.security.config.CustomSecurityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Created by Administrator on 2017/2/12 0012.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    protected UserDetailsService userDetailsService;
    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;
    @Autowired
    private CustomSecurityConstant securityConstant;
    @Autowired
    private CustomAuthenticationHandlers authenticationHandlers;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/oauth/**", "/css/**", "/js/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/authentication/require")
            .permitAll()
            .and()
            .logout()
            .logoutUrl(securityConstant.getUri().getLogout())
            .permitAll()
            .and()
            .addFilterBefore(
                new CustomWebAuthenticationFilter(
                    super.authenticationManager(),
                    securityConstant.getUri().getLoginForm(),
                    securityConstant.getParameterName().getCaptchaCode()
                ),
                UsernamePasswordAuthenticationFilter.class
            )
            .exceptionHandling()
            .authenticationEntryPoint(authenticationHandlers.getAuthenticationEntryPoint())
            .accessDeniedHandler(authenticationHandlers.getAccessDenyHandler())
        ;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticationProvider);
    }

}